﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using Newtonsoft.Json.Linq;
using TaggerApp.ORD;
namespace TaggerApp.Authentication
{

    public class oAuthLiveImpl : oAuth
    {
        public void initialLogin(HttpResponse response) {
            String url = Constants.LIVE_URL + @"client_id=" + Constants.LIVE_CLIENT_ID + "&response_type=" + Constants.RESPONSE_TYPE_CODE + "&scope=" + Constants.SCOPE + "&display=" + Constants.DISPLAY + "&redirect_uri=" + Constants.LIVE_REDIRECT;
            response.Redirect(url);
        }
        public User getUserInfo(string token) {
            string url = Constants.LIVE_USER_INFO_URL + token;
            WebClient serviceRequest = new WebClient();
            string json = serviceRequest.DownloadString(new Uri(url));
            var jsonObj = JObject.Parse(json);
            string fName = (string)jsonObj["first_name"];
            string lName = (string)jsonObj["last_name"];
            string id = (string)jsonObj["id"];
            string email = (string)jsonObj["emails"]["account"];
            string role;
            using (mstaggerEntities context = new mstaggerEntities()) {
                role = context.getRole(email).FirstOrDefault();
            }
            if (role == null)
            {
                role = "user";
            }
            User myUser = new User(fName, lName, id, email, role);
            return myUser;
        }
        public string getToken(HttpRequest request) {
            string accessCode = request.QueryString["code"];
            string url = Constants.LIVE_TOKEN + @"client_id=" + Constants.LIVE_CLIENT_ID + "&redirect_uri=" + Constants.LIVE_REDIRECT + "&client_secret=" + Constants.LIVE_CLIENT_SECRET + "&code=" + accessCode + "&grant_type=authorization_code";
            WebClient serviceRequest = new WebClient();
            string response = serviceRequest.DownloadString(new Uri(url));
            var jsonObj = JObject.Parse(response);
            string token = (string)jsonObj["access_token"];
            return token;
        }
        public void logout(HttpResponse response)
        {
            string url = Constants.LIVE_LOGOUT + @"client_id=" + Constants.LIVE_CLIENT_ID + "&redirect_uri=" + Constants.LIVE_REDIRECT;
            response.Redirect(url);
        }
    }
}